﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using Spotted.DBReference;
using System.ServiceModel;
using System.Text.RegularExpressions;
using Spotted.Storage.Blobs;
using System.Threading;


namespace Spotted
{
    public partial class MainPage : PhoneApplicationPage
    {
        Camera camera;
        string user_username;
        string user_userpass;
        Service1Client client = null;
        private App app = Application.Current as App;
        private static Boolean showProgress;
        private BlobAPI blob;
        private static bool ShowProgress
        {
            get{return showProgress;}
            set { showProgress = value; }
        }

        

        // Constructor
        public MainPage()
        {
            
            InitializeComponent();
           

            client = new Service1Client();
       
            try
        {
            camera = new Camera(new EventHandler<PhotoResult>(cameraCaptureTask_Completed)) ;
            

        }
            catch (System.InvalidOperationException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

       

        public  void cameraCaptureTask_Completed(object sender, PhotoResult e)
        {
            blob = new BlobAPI(new EventHandler<AddImageCompletedEventArgs>(serviceClient_AddImageCompleted));
            
            if (e.TaskResult == TaskResult.OK)
            {

                ShowProgress = true;
                ContentPanel.Visibility = System.Windows.Visibility.Collapsed;
                Waiting.Visibility = System.Windows.Visibility.Visible;

           
                     //upload to blob
               
                blob.LoadPhotoInfoToBlob(e);
                blob.uploadPhoto();             
               }
        }


        public void serviceClient_AddImageCompleted(object sender, AddImageCompletedEventArgs e)
        {

            app.NewImage = new SImage()
            {

                imageId = e.Result,
                imageUri = blob.blob_Url,
                datecreated = DateTime.Now,
                Area = blob.Area,
                Asymmetry = -1,
                Average_B = -1,
                Average_G = -1,
                Average_H = -1,
                Average_I = -1,
                Average_R = -1,
                Average_S = -1,
                Boundary_irregularity = -1,
                Diameter = -1,
                Dominant_B = -1,
                Dominant_G = -1,
                Dominant_H = -1,
                Dominant_I = -1,
                Dominant_R = -1,
                Dominant_S = -1,
                Energy = -1,
                Entropy = -1,
                Homogeneity = -1,
                Inertia = -1,
                Num_of_subregions = -1,
                Num_of_subregion_types = -1,
                Perimeter = blob.Perimeter,
                benign = Boolean.Parse(blob.melanoma.Replace("\n",""))
            };
            Deployment.Current.Dispatcher.BeginInvoke(() =>
    {
        Waiting.Visibility = System.Windows.Visibility.Collapsed;
        this.NavigationService.Navigate(new Uri("/Spotted;component/Views/newPinSpotPage.xaml", UriKind.Relative));

    });
        }



        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            var lastPage = NavigationService.BackStack.FirstOrDefault();

            if(lastPage != null)
            {
                if(lastPage.Source.ToString() == "/Spotted;component/Views/newPinSpotPage.xaml" ||
                    lastPage.Source.ToString() == "/Spotted;component/Views/sharePage.xaml")
                {
                    user.Visibility = System.Windows.Visibility.Collapsed;
                    ContentPanel.Visibility = System.Windows.Visibility.Visible;
                }
            
                if(lastPage.Source.ToString() == "/Spotted;component/Views/newPinSpotPage.xaml" )

                   
                {
                    if(app.navigatedFromCompare == true)
                    {
                        app.navigatedFromCompare = false;
                    }

                    else if(app.navigatedFromNewSpot == true)
                    {
                        app.navigatedFromNewSpot = false;
                    }

                    else if(app.navigatedFromShare == true)
                    {
                        app.navigatedFromShare = false;
                    }
                }

            }
        }
        private void image1_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }


        private void newSpot_Click(object sender, RoutedEventArgs e)
        {

            app.navigatedFromNewSpot = true;
            try
            {
                camera.show();
               
                


            }
            catch (System.InvalidOperationException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

      

        private void compare_Click(object sender, RoutedEventArgs e)
        {
            app.navigatedFromCompare = true;
            this.NavigationService.Navigate(new Uri("/Spotted;component/Views/newPinSpotPage.xaml", UriKind.Relative));

        }

        private void medicalInformation_Click(object sender, RoutedEventArgs e)
        {

        }

        private void notification_Click(object sender, RoutedEventArgs e)
        {

        }

        private void share_Click(object sender, RoutedEventArgs e)
        {
            app.navigatedFromShare = true;
        }

        private void hyperlinkButton1_Click(object sender, RoutedEventArgs e)
        {

        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {

        }



        private void userLogin_Click(object sender, RoutedEventArgs e)
        {
            user.Visibility = System.Windows.Visibility.Collapsed;
            logIn.Visibility = System.Windows.Visibility.Visible;
            username_text.Focus();
        }

        private void userSignup_Click(object sender, RoutedEventArgs e)
        {
            user.Visibility = System.Windows.Visibility.Collapsed;
            newUser.Visibility = System.Windows.Visibility.Visible;
            new_username_text.Focus();

        }

        private void logout_Click(object sender, RoutedEventArgs e)
        {
            
            app.Logged_User = null;
       
            for(int i = 0; i < NavigationService.BackStack.Count<System.Windows.Navigation.JournalEntry>(); i++)
            {
                NavigationService.RemoveBackEntry();
            }
            ContentPanel.Visibility = System.Windows.Visibility.Collapsed;
            user.Visibility = System.Windows.Visibility.Visible;
        }
        
        
        
        // log in

        private void username_text_TextChanged(object sender, TextChangedEventArgs e)
        {
            user_username = username_text.Text;
        }

       private void pass_text_PasswordChanged(object sender, RoutedEventArgs e)
        {
            user_userpass = pass_text.Password;
        } 
        private void loginOK_Click(object sender, RoutedEventArgs e)
        {
            loginOK.Visibility = System.Windows.Visibility.Collapsed;
            retrieving_data.Visibility = System.Windows.Visibility.Visible;
            client.LoginUserCompleted += new EventHandler<LoginUserCompletedEventArgs>(client_LoginUserCompleted);
            client.LoginUserAsync(user_username, user_userpass);
        }

        void client_LoginUserCompleted(object sender, LoginUserCompletedEventArgs e)
        {
            client.LoginUserCompleted -= new EventHandler<LoginUserCompletedEventArgs>(client_LoginUserCompleted);

            if(e.Result == -1)
            {
                username_text.Text = "";
                user_username = "";
                pass_text.Password = "";
                user_userpass = "";

                logIn.Visibility = System.Windows.Visibility.Collapsed;
                loginOK.Visibility = System.Windows.Visibility.Visible;
                retrieving_data.Visibility = System.Windows.Visibility.Collapsed;
                logInFailed.Visibility = System.Windows.Visibility.Visible;
            }

            else
            {
               
                app.Logged_User = new LoggedUser();
                app.Logged_User.CurrentUser = new SUser();
                app.Logged_User.UserSpots = new List<SSpot>();
                app.Logged_User.AllUserImagesPerSpot = new Dictionary<int, List<SImage>>();
                app.Logged_User.UserSpotsBack = new List<SSpot>();
                app.Logged_User.UserSpotsFront = new List<SSpot>();
                app.Logged_User.CurrentUser.UserId = e.Result;
                app.Logged_User.CurrentUser.UserName = user_username;
                app.Logged_User.CurrentUser.Password = user_userpass;

                client.getUserSpotsCompleted += new EventHandler<getUserSpotsCompletedEventArgs>(client_getUserSpotsCompleted);
                client.getUserSpotsAsync(app.Logged_User.CurrentUser.UserId);
            }
           
        }

        private void logInFailed_OK_Click(object sender, RoutedEventArgs e)
        {
            logInFailed.Visibility = System.Windows.Visibility.Collapsed;
            logIn.Visibility = System.Windows.Visibility.Visible;
            username_text.Focus();
            
        }
        void client_getUserSpotsCompleted(object sender, getUserSpotsCompletedEventArgs e)
        {
            client.getUserSpotsCompleted -= new EventHandler<getUserSpotsCompletedEventArgs>(client_getUserSpotsCompleted);
            
            app.Logged_User.UserSpots = e.Result;
            app.Logged_User.setUserSpots_Front_Back();

            client.getAllUserImagesPerSpotCompleted += new EventHandler<getAllUserImagesPerSpotCompletedEventArgs>(client_getAllUserImagesPerSpotCompleted);
            client.getAllUserImagesPerSpotAsync(app.Logged_User.CurrentUser.UserId);       
        }

        
        void client_getAllUserImagesPerSpotCompleted(object sender, getAllUserImagesPerSpotCompletedEventArgs e)
        {
            client.getAllUserImagesPerSpotCompleted -= new EventHandler<getAllUserImagesPerSpotCompletedEventArgs>(client_getAllUserImagesPerSpotCompleted);
           
            app.Logged_User.AllUserImagesPerSpot = e.Result;

            logIn.Visibility = System.Windows.Visibility.Collapsed;
            logInSuccess.Visibility = System.Windows.Visibility.Visible;
        }


        private void logInSuccessOK_Click(object sender, RoutedEventArgs e)
        {
            username_text.Text = "";           
            pass_text.Password = "";
           
            logInSuccess.Visibility = System.Windows.Visibility.Collapsed;
            ContentPanel.Visibility = System.Windows.Visibility.Visible;
        }

        //====================================================================================
        // sign up


        private void new_username_text_TextChanged(object sender, TextChangedEventArgs e)
        {
           
            user_username = new_username_text.Text;
        }
       

        private void new_pass_text_PasswordChanged(object sender, RoutedEventArgs e)
        {
            user_userpass = new_pass_text.Password;
        }

        private void addNewUser_Click(object sender, RoutedEventArgs e)
        {
            addNewUser.Visibility = System.Windows.Visibility.Collapsed;
            creatingUser.Visibility = System.Windows.Visibility.Visible;

            //Regex.IsMatch(input, @"^[a-zA-Z0-9]+$");

            if(user_username.Length < 6)
            {
                MessageBox.Show("Username must be at least 6 characters length.","", MessageBoxButton.OK);
                new_username_text.Text = "";
                user_username = "";
                new_pass_text.Password = "";
                user_userpass = "";
                newUser.Visibility = System.Windows.Visibility.Visible;
                new_username_text.Focus();
            }

            else if(!Regex.IsMatch(user_username, @"^[a-zA-Z0-9]+$"))
            {
                MessageBox.Show("Illegal username. You can use only letters (a-z,A-Z) and numbers (0-9)", "", MessageBoxButton.OK);
                new_username_text.Text = "";
                user_username = "";
                new_pass_text.Password = "";
                user_userpass = "";
                newUser.Visibility = System.Windows.Visibility.Visible;
                new_username_text.Focus();
            }


            else if(user_userpass.Length < 6)
            {
                MessageBox.Show("Password must be at least 6 characters length.", "", MessageBoxButton.OK);
                new_username_text.Text = "";
                user_username = "";
                new_pass_text.Password = "";
                user_userpass = "";
                newUser.Visibility = System.Windows.Visibility.Visible;
                new_username_text.Focus();
            }

            else if(!Regex.IsMatch(user_userpass, @"^[a-zA-Z0-9]+$"))
            {
                MessageBox.Show("Illegal password. You can use only letters (a-z,A-Z) and numbers (0-9)", "", MessageBoxButton.OK);
                new_username_text.Text = "";
                user_username = "";
                new_pass_text.Password = "";
                user_userpass = "";
                newUser.Visibility = System.Windows.Visibility.Visible;
                new_username_text.Focus();
            }

            else
            {
                client.AddUserCompleted += new EventHandler<AddUserCompletedEventArgs>(client_AddUserCompleted);
                client.AddUserAsync(user_username, user_userpass);
            }
        }

        void client_AddUserCompleted(object sender, AddUserCompletedEventArgs e)
        {
            client.AddUserCompleted -= new EventHandler<AddUserCompletedEventArgs>(client_AddUserCompleted);

            if(e.Result == -1)
            {
                new_username_text.Text = "";
                user_username = "";
                new_pass_text.Password = "";
                user_userpass = "";
                newUser.Visibility = System.Windows.Visibility.Collapsed;
                usernameExist.Visibility = System.Windows.Visibility.Visible;
            }

            else
            {
               
                app.Logged_User = new LoggedUser();
                app.Logged_User.CurrentUser = new SUser();
                app.Logged_User.UserSpots = new List<SSpot>();
                app.Logged_User.AllUserImagesPerSpot = new Dictionary<int, List<SImage>>();
                app.Logged_User.UserSpotsBack = new List<SSpot>();
                app.Logged_User.UserSpotsFront = new List<SSpot>();
                app.Logged_User.CurrentUser.UserId = e.Result;
                app.Logged_User.CurrentUser.UserName = user_username;
                app.Logged_User.CurrentUser.Password = user_userpass;

                newUser.Visibility = System.Windows.Visibility.Collapsed;
                addNewUser.Visibility = System.Windows.Visibility.Visible;
                creatingUser.Visibility = System.Windows.Visibility.Collapsed;
                newUserSuccess.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void newUserSuccessOK_Click(object sender, RoutedEventArgs e)
        {
            new_username_text.Text = "";
            new_pass_text.Password = "";
          
            newUserSuccess.Visibility = System.Windows.Visibility.Collapsed;
            ContentPanel.Visibility = System.Windows.Visibility.Visible;

        }
        private void chooseUsernameOK_Click(object sender, RoutedEventArgs e)
        {
            usernameExist.Visibility = System.Windows.Visibility.Collapsed;
            newUser.Visibility = System.Windows.Visibility.Visible;
            new_username_text.Focus();
            
        }

        private void newSpotInfo_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Hold the camera 15 cm away from your skin in bright natural light without shadows", 
                "How to take a picture", MessageBoxButton.OK);
        }

        private void new_usernameInfo_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Username must be at least 6 characters length. You can use letters (a-z,A-Z) and numbers (0-9).",
                "How to choose username", MessageBoxButton.OK);
        }

        private void passInfo_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Password must be at least 6 characters length. You can use letters (a-z,A-Z) and numbers (0-9).",
               "How to choose password", MessageBoxButton.OK);
        }

        


      
    }
}